Home:ALL Converter>References and URL rules in Flask

References and URL rules in Flask

Ask Time:2015-03-31T03:03:15         Author:user3448282

Json Formatter

I've got a problem with my simple app in Flask. I want to write a registration page, that connect with datebase by SQLAlchemy. I've got app.py file that look like this:

import flask
import settings
import os
from flask_sqlalchemy import SQLAlchemy

# Views
from main import Main
from login import Login
from remote import Remote
from register import Register
#from models import User
#from models import Task

app = flask.Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database.db'
db = SQLAlchemy(app)


# Routes
app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods=["GET"])
app.add_url_rule('/<page>/',
                 view_func=Main.as_view('page'),
                 methods=["GET"])
app.add_url_rule('/login/',
                 view_func=Login.as_view('login'),
                 methods=["GET", "POST"])
app.add_url_rule('/remote/',
                 view_func=Remote.as_view('remote'),
                 methods=['GET', 'POST'])
app.add_url_rule('/register/',
                 view_func=Register.as_view('register'),
                 methods=['GET', 'POST'])

@app.errorhandler(404)
def page_not_found(error):
    return flask.render_template('404.html'), 404

app.debug = True
app.run()

So, as you can see I have URL rules in this file and now I want to use db variable in Register view, so I need import it there, my code for this file looks like this:

import flask, flask.views
from app import db

class Register(flask.views.MethodView):
    def get(self):
        return flask.render_template('register.html')

    def post(self):
        new_user = User(username = request.form['username'], 
                        password = request.form['passwd']
        db.session.add(new_user)
        db.session.commit()
        return flask.redirect(flask.url_for('index'))

In that case I get error, cause I have "tied" references, in app file is:

from register import Register

but in Register file is

from app import db

So it, obviously can't work, my solutions is to add URL rule in Register file. But I don't know how. Could you anyone help me?

Sorry for my confusing title, but I just getting started with Flask and I dnon't know how to name it.

Author:user3448282,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29354141/references-and-url-rules-in-flask
yy